package com.cow.net.tcp;




import com.cow.net.tcp.adpter.ParseAdpter;
import com.cow.net.tcp.adpter.ParseAdpterFactory;
import com.cow.net.tcp.domain.DeviceValue;
import com.cow.net.tcp.domain.TypeData;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Description:
 * Author:Giousa
 * Date:2017/2/9
 * Email:65489469@qq.com
 */
public class ServerHandler extends CustomHeartbeatHandler {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    public ServerHandler() {
        super("server");
    }

    @Override
    protected void handleData(ChannelHandlerContext channelHandlerContext, Object msg) {
        DeviceValue.Request deviceValue = (DeviceValue.Request) msg;
       logger.info("server 接收数据:"+"orgid:"+deviceValue.getCompanyId()+"内容:"+deviceValue.getContext() +"dataType:"+deviceValue.getDataType());


        ParseAdpter parseAdpter =  ParseAdpterFactory.getInstance().loadParseAdpterByDataType(deviceValue.getDataType());
        String re = parseAdpter.parse(deviceValue);

        if(re != null)
        {
        DeviceValue.Request.Builder s  =DeviceValue.Request.newBuilder();
            s.setDataType(TypeData.DATA);
        s.setPackageType(TypeData.REPLY);
        s.setContext(re);
        channelHandlerContext.writeAndFlush(s);
        }
      //  System.out.println("server 发送数据:"+s.toString());
    }

    @Override
    protected void handleReaderIdle(ChannelHandlerContext ctx) {
        super.handleReaderIdle(ctx);
        logger.info("---client " + ctx.channel().remoteAddress().toString() + " reader timeout, close it---");
        ctx.close();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        logger.info(name+" exception"+cause.toString());
    }
}